﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace THO7AlgoritmTimerApplication {
    class Remove_filter : VisionAlgorithm {
        int filter_groote = 0;
        public Remove_filter(String name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            filter_groote = getMarge();
            Bitmap returnImage = new Bitmap(sourceImage);
            
            Rectangle rect = new Rectangle(0, 0, returnImage.Width, returnImage.Height);
            BitmapData myBmpData = returnImage.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            IntPtr ptr = myBmpData.Scan0;
            int numBytes = returnImage.Width * returnImage.Height * 3;
            byte[] rgbValues = new byte[numBytes];
            byte[] newrgbValues = new byte[numBytes];
            Marshal.Copy(ptr, rgbValues, 0, numBytes);
            
            int regelGroote = returnImage.Width * 3;
            for (int imagex = (filter_groote / 2); imagex < sourceImage.Width - (filter_groote / 2); imagex++){
                for (int imagey = (filter_groote / 2); imagey < sourceImage.Height - (filter_groote / 2); imagey++){
                    int counter = 0;
                    int grey = 0;
                    for (int y = imagey - (filter_groote / 2); y <= imagey + (filter_groote / 2); y++){
                        for (int x = imagex - (filter_groote / 2); x <= imagex + (filter_groote / 2); x++){
                            grey += (int)rgbValues[x * 3 + (y * regelGroote)];
                            counter++;
                        }
                    }
                    if ((grey / counter) > 160) {
                        newrgbValues[imagex * 3 + (imagey * regelGroote)] = (byte)255;
                        newrgbValues[imagex * 3 + (imagey * regelGroote) + 1] = (byte)255;
                        newrgbValues[imagex * 3 + (imagey * regelGroote) + 2] = (byte)255;
                    }
                }
            }
            Marshal.Copy(newrgbValues, 0, ptr, numBytes);
            returnImage.UnlockBits(myBmpData);
            return returnImage;
        }
    }
}

